< previous page page_483 next page >

Page 483
Opening a Random Access File
The main difference between opening a random access file and a sequential file is that you must specify the record length in the Open statement. The record length for a user-defined data type can be obtained by using the Len statement on a variable of that type, as in the following example:
Dim emp1 As Employee
Open "D:\EMPINFO.DAT" for Random As #1 Len = Len(emp1)
The preceding line of code opens the file EMPINFO.DAT for random access. The Len= part of the Open statement tells Visual Basic that subsequent reads and writes to the file will assume that the file contains only records the length of emp1.
Adding Records with Put
After you open a file for random access, use the Put statement to store records in the file. The syntax of the Put statement is as follows:
Put filenumber,[recnumber],variablename
The following code uses the Put statement in a For loop to write five records of type Employee to file #1:
For i = 1 To 5
    emp1.LName = InputBox$("Enter Last Name")
    emp1.Fname = InputBox$("Enter First Name")
    emp1.Title = InputBox$("Enter Title")
    emp1.EmpID = i
    Put #1, , emp1
Next i
Notice the omission of the recnumber parameter, which specifies the location in the file where the new record should be written. This approach is useful for altering existing records in a file. If you do not specify this parameter, the record is written to the current file pointer location.
Retrieving Records with Get
To retrieve records from a random file, use the Get statement. The Get statement can be used to read information back into your record type, as in the following example that reads record number 4 in the file into the variable emp1 and then displays the Title field:
Get #1, 4, emp1
MsgBox "Employee title is " & emp1.Title
The syntax of the Get statement is similar to Put:
Get filenumber,[recnumber],variablename
If you omit the recnumber parameter, Get behaves like the sequential Line Input statement; that is, each subsequent Get reads the next record.

 
< previous page page_483 next page >